<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/06/02
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use think\Db;
use app\common\builder\ZBuilder;
/**
 * 供应商管理
 * @package app\cms\admin
 */
class Supplier extends Admin
{
    /**
     * 首页
     * @author  dou<51779987@qq.com>
     * @return mixed
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        //获取筛选
        $map = $this->getMap();
        //数据获取
        $data = input();
        //数据列表
        $data_list = model('ErpSupplier', 'model') -> where($map) -> order('sort asc, create_time desc') -> paginate();
		foreach($data_list as $key => $value){
			$data_list[$key]['settlement_cycle'] = $value['jiesuan_type'] == 1 ? $value['settlement_cycle'] . '天' : $value['jiesuan_date'] . '号';
		}
		
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('供应商管理') // 设置页面标题
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('erp_supplier') // 设置数据表名
            ->addColumns([ // 批量添加列
                // ['__INDEX__', '序号'],
                // ['id', '供应商ID'],
                ['title', '供应商名称'],
                ['code', '供应商编码'],
                ['jiesuan_type', '结算方式', [1 => '货到N日内付款', 2 => '月结 当月 固定日期', 3 => '月结 次月 固定日期']],
                ['settlement_cycle', '到货天数/月结日期'],
                ['corporate_name', '公司名称'],
                ['corporate_address', '公司地址'],
                // ['remarks', '备注'],
                ['sort', '排序', 'text.edit'],
                // ['create_time', '创建时间', 'datetime'],
                // ['store_status', '状态', 'switch'],
                ['right_button', '操作', 'btn']
            ])
			->setSearchArea([
				['text', 'id', '供应商ID'],
                ['text', 'title', '供应商名称', 'like'],
                ['text', 'code', '供应商编码', 'like'],
				['daterange', 'create_time', '创建时间'],
            ])
            // ->setSearch(['id' => '供应商ID', 'title' => '供应商名称', 'code' => '供应商编码']) // 设置搜索参数
            ->addTopButton('add', '', ['area' => ['50%', '80%']]) // 添加授权按钮
            ->addRightButton('edit', '', ['area' => ['50%', '80%']]) // 批量添加右侧按钮
            ->addRightButton('delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面

    }

    /**
     * 添加
     * @author  dou<51779987@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add(){
        // 保存数据
        if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post();
            $title              = isset($data['title']) ? $data['title'] : '';
            $settlement_cycle  	= isset($data['settlement_cycle']) ? $data['settlement_cycle'] : '';
            $jiesuan_type  	    = isset($data['jiesuan_type']) ? $data['jiesuan_type'] : 0;
            $jiesuan_date1      = isset($data['jiesuan_date1']) ? $data['jiesuan_date1'] : '';
            $jiesuan_date2      = isset($data['jiesuan_date2']) ? $data['jiesuan_date2'] : '';
            
            $corporate_name     = isset($data['corporate_name']) ? $data['corporate_name'] : '';
            $corporate_address  = isset($data['corporate_address']) ? $data['corporate_address'] : '';
            $remarks  		    = isset($data['remarks']) ? $data['remarks'] : '';
            $sort  		        = isset($data['sort']) ? $data['sort'] : '';
			
            $supplier_type  	= isset($data['supplier_type']) ? $data['supplier_type'] : 0;
            $tax_rate  		    = isset($data['tax_rate']) ? $data['tax_rate'] : '';
            $bank_account  		= isset($data['bank_account']) ? $data['bank_account'] : '';
            $tax_code  		    = isset($data['tax_code']) ? $data['tax_code'] : '';
            $rebate  		    = isset($data['rebate']) ? $data['rebate'] : '';

            //数据验证
            $Validate = validate('Supplier', 'validate');
            if( !$Validate -> scene('supplier_add') -> check($data) ){
                $this->error($Validate -> getError());
            }
            $jiesuan_date = '';
            switch ($jiesuan_type) {
                case '2':
                    $jiesuan_date = $jiesuan_date1;
                    break;
                case '3':
                    $jiesuan_date = $jiesuan_date2;
                    break;
                default:
                    # code...
                    break;
            }
            $rel = model('ErpSupplier','model') -> addData($title, $settlement_cycle, $corporate_name, $corporate_address, $remarks, $sort, $supplier_type, $tax_rate, $bank_account, $tax_code, $jiesuan_type, $jiesuan_date, $rebate);

            if($rel['code'] == 200){
				$supplier_id = $rel['data'];
				$code = sprintf("%04d", $supplier_id);
				
				$map = [];
				$map['id'] = $supplier_id;
				
				$data = [];
				$data['code'] = $code;
				$res = model('ErpSupplier') -> update($data, $map);
				if(!$res){
					$this->error($rel['message']);
				}
                $this->success('新增成功', '', '_parent_reload');
            }else{
                $this->error($rel['message']);
            }

        }

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增供应商') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['text', 'title', '供应商名称','必填'],
                ['radio','jiesuan_type', '结算方式', '', ['1' => '货到N日内付款', '2' => '月结 当月 固定日期', '3' => '月结 次月 固定日期'], 1],
                ['number', 'settlement_cycle', '货到几日付款', '请输入结算天数'],
                ['number', 'jiesuan_date1', '结算日期', '当月 结算日期', '', '0', '31', '1'],
                ['number', 'jiesuan_date2', '结算日期', '次月 结算日期', '', '0',  '31', '1'],
                ['text', 'corporate_name', '公司名称','请输入公司名称'],
                ['text', 'corporate_address', '公司地址','请输入公司地址'],
				['select', 'supplier_type', '经营方式','请选择经营方式', [1 => '经销', 2 => '代销', 3 => '联营']],
                ['text', 'tax_rate', '税率(%)','请输入税率的百分比'],
                ['text', 'bank_account', '银行账户','请输入银行账户'],
                ['text', 'tax_code', '税号','请输入税号'],
                ['text', 'rebate', '返利(%)','请输入返利的百分比'],
                
            ])
            ->setTrigger('jiesuan_type', 1, 'settlement_cycle')
            ->setTrigger('jiesuan_type', 2, 'jiesuan_date1')  
            ->setTrigger('jiesuan_type', 3, 'jiesuan_date2')     
            ->addTextarea('remarks', '备注[:请输入备注信息]')
            ->addText('sort', '排序', '', 100)
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id 供应商id
     * @author dou <51779987@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function edit($id = null)
    {
        if ($id === null) $this->error('缺少参数');
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['id'] = $id;
			$title              = isset($data['title']) ? $data['title'] : '';
            $settlement_cycle  	= isset($data['settlement_cycle']) ? $data['settlement_cycle'] : '';
            $jiesuan_type  	    = isset($data['jiesuan_type']) ? $data['jiesuan_type'] : 0;
            $jiesuan_date1      = isset($data['jiesuan_date1']) ? $data['jiesuan_date1'] : '';
            $jiesuan_date2      = isset($data['jiesuan_date2']) ? $data['jiesuan_date2'] : '';
            
            $corporate_name     = isset($data['corporate_name']) ? $data['corporate_name'] : '';
            $corporate_address  = isset($data['corporate_address']) ? $data['corporate_address'] : '';
            $remarks  		    = isset($data['remarks']) ? $data['remarks'] : '';
            $sort  		        = isset($data['sort']) ? $data['sort'] : '';
			
            $supplier_type  	= isset($data['supplier_type']) ? $data['supplier_type'] : 0;
            $tax_rate  		    = isset($data['tax_rate']) ? $data['tax_rate'] : '';
            $bank_account  		= isset($data['bank_account']) ? $data['bank_account'] : '';
            $tax_code  		    = isset($data['tax_code']) ? $data['tax_code'] : '';
            $rebate  		    = isset($data['rebate']) ? $data['rebate'] : '';

            //数据验证
            $Validate = validate('Supplier', 'validate');
            if( !$Validate -> scene('supplier_edit') -> check($data) ){
                $this->error($Validate -> getError());
            }
			
			if( !$Validate -> scene('supplier_add') -> check($data) ){
                $this->error($Validate -> getError());
            }
            $jiesuan_date = '';
            switch ($jiesuan_type) {
                case '2':
                    $jiesuan_date = $jiesuan_date1;
					$settlement_cycle = 0;
                    break;
                case '3':
                    $jiesuan_date = $jiesuan_date2;
					$settlement_cycle = 0;
                    break;
                default:
                    # code...
                    break;
            }
			if($jiesuan_type == 1) $jiesuan_date = 0;
			
            $rel = model('ErpSupplier','model') -> editData($id, $title, $settlement_cycle, $corporate_name, $corporate_address, $remarks, $sort, $supplier_type, $tax_rate, $bank_account, $tax_code, $jiesuan_type, $jiesuan_date, $rebate);
			

            if($rel['code'] == 200){
                $this->success('编辑成功', '', '_parent_reload');
            }else{
                $this->error($rel['message']);
            }

        }

        $info = model('ErpSupplier', 'model') -> find($id);
		
		$info['jiesuan_date1'] = $info['jiesuan_type'] == 2 ? $info['jiesuan_date'] : 0;
		$info['jiesuan_date2'] = $info['jiesuan_type'] == 3 ? $info['jiesuan_date'] : 0;
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑供应商')
            ->addFormItems([
                ['text', 'title', '供应商名称','必填'],
				['radio','jiesuan_type', '结算方式', '', ['1' => '货到N日内付款', '2' => '月结 当月 固定日期', '3' => '月结 次月 固定日期'], 1],
				['number', 'settlement_cycle', '货到几日付款', '请输入结算天数'],
                ['number', 'jiesuan_date1', '结算日期', '当月 结算日期', '', '0', '31', '1'],
                ['number', 'jiesuan_date2', '结算日期', '次月 结算日期', '', '0',  '31', '1'],
                ['text', 'corporate_name', '公司名称','请输入公司名称'],
                ['text', 'corporate_address', '公司地址','请输入公司地址'],
				['select', 'supplier_type', '经营方式','请选择经营方式', [1 => '经销', 2 => '代销', 3 => '联营']],
                ['text', 'tax_rate', '税率(%)','请输入税率的百分比'],
                ['text', 'bank_account', '银行账户','请输入银行账户'],
                ['text', 'tax_code', '税号','请输入税号'],
				['text', 'rebate', '返利(%)','请输入返利的百分比'],
            ])
            ->addTextarea('remarks', '备注[:请输入备注信息]')
			->setTrigger('jiesuan_type', 1, 'settlement_cycle')
            ->setTrigger('jiesuan_type', 2, 'jiesuan_date1')  
            ->setTrigger('jiesuan_type', 3, 'jiesuan_date2')     
            ->addText('sort', '排序')
            ->setFormData($info)
            ->fetch();
    }



    /**
     * 详细
     * @param null $id 供应商id
     * @author dou <51779987@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function details($id = []){
        if ($id === null) $this->error('缺少参数');
        $info = model('ErpSupplier', 'model') -> find($id);

        $info['jiesuan_date1'] = $info['jiesuan_type'] == 2 ? $info['jiesuan_date'] : 0;
        $info['jiesuan_date2'] = $info['jiesuan_type'] == 3 ? $info['jiesuan_date'] : 0;
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('供应商详细')
            ->addFormItems([
                ['text', 'title', '供应商名称','','','','readonly="readonlys"'],
                ['select','jiesuan_type', '结算方式', '', ['1' => '货到N日内付款', '2' => '月结 当月 固定日期', '3' => '月结 次月 固定日期'], '','disabled="disabled"'],
                ['text', 'settlement_cycle', '货到几日付款','','','','readonly="readonlys"'],
                ['text', 'jiesuan_date1', '结算日期', '当月 结算日期','','','readonly="readonlys"'],
                ['text', 'jiesuan_date2', '结算日期', '次月 结算日期', '','','readonly="readonlys"'],
                ['text', 'corporate_name', '公司名称','','','','readonly="readonlys"'],
                ['text', 'corporate_address', '公司地址','','','','readonly="readonlys"'],
                ['select', 'supplier_type', '经营方式','', [1 => '经销', 2 => '代销', 3 => '联营'],'','disabled="disabled"'],
                ['text', 'tax_rate', '税率(%)','','','','readonly="readonlys"'],
                ['text', 'bank_account', '银行账户','','','','readonly="readonlys"'],
                ['text', 'tax_code', '税号','','','','readonly="readonlys"'],
                ['text', 'rebate', '返利(%)','','','','readonly="readonlys"'],
            ])
            ->addTextarea('remarks', '备注','','','disabled="disabled"')
            ->setTrigger('jiesuan_type', 1, 'settlement_cycle')
            ->setTrigger('jiesuan_type', 2, 'jiesuan_date1')
            ->setTrigger('jiesuan_type', 3, 'jiesuan_date2')
            ->addText('sort', '排序','','','','readonly="readonlys"')
            ->hideBtn(['submit', 'back'])
            ->setFormData($info)
            ->fetch();
    }


}